package rabbitmq.A03publisAndSubscribe;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/***
 * 广播模式：发布---订阅模式
 * 一条消息会分发非交换器绑定的所有queue
 */
public class Publish {
    private static final String EXCHANGE_NAME="logs";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.1.100");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        try (Connection connection = connectionFactory.newConnection();
             Channel channel = connection.createChannel()) {
            channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);

            String message = "Noidler:Hello World![%d]";
            int curr = 1;
            while (true) {
                TimeUnit.MILLISECONDS.sleep(50);
                channel.basicPublish(EXCHANGE_NAME, "", null, String.format(message,curr++).getBytes());
//                System.out.println(" [Noidler] Sent '" + message + "'");
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
